package com.hejia.alauda.jms;

import com.hejia.alauda.entity.Product;
import com.hejia.alauda.service.BalanceAndFinancingService;
import com.hejia.alauda.service.ProductService;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import javax.annotation.Resource;
import javax.jms.Message;
import javax.jms.MessageListener;

/**
 * 产品售完消息监听器
 * @author hyr
 *
 */
public class ProductSoldOutMessageListener implements MessageListener {

	private static final Log Logger = LogFactory.getLog(ProductSoldOutMessageListener.class);
	
	@Resource
	private BalanceAndFinancingService balanceAndFinancingService;
	
	@Resource
	private ProductService productService;
	
	@Override
	public void onMessage(Message message) {
		
		try {
			
			// 产品销售结束，未售完入库
			Logger.debug("接收产品销售结束消息 " + message);
			
			if(!(message instanceof ActiveMQTextMessage)) {
				return;
			}
			
			ActiveMQTextMessage textMessage = (ActiveMQTextMessage)message;
			
			ObjectMapper mapper = new ObjectMapper();
			
			JsonNode jsonNode = mapper.readTree(textMessage.getText());
			String serial = jsonNode.get("serial").asText();
			Product product = this.productService.getProductBySerial(serial);
			if(product == null){
				Logger.warn("找不到产品 序列号：" + serial);
				return;
			}
			
			balanceAndFinancingService.productSellCloseAdjustStock(product.getId());
			Logger.debug("销售结束产品入库结束");
			
		} catch (Exception e) {
			Logger.error("销售结束产品入库执行失败", e);
		}
	}
}
